package com.bitBusy.manageyourriches.alarmSystem;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.bitBusy.manageyourriches.activity.AlarmActivity;
import com.bitBusy.manageyourriches.activity.HomeActivity;
import com.bitBusy.manageyourriches.database.contactClasses.PaymentReminder;
import com.bitBusy.manageyourriches.database.managers.DatabaseInteractor;

/**
 * @author SumaHarsha
 *
 */
public class AlarmManagement {

	private static final Context ALARMCONTEXT = HomeActivity.getAppContext();
 
	public static boolean setAlarm(PaymentReminder the_reminder)
	{
		if (the_reminder != null)
		{
		  AlarmManager alarmManager =(AlarmManager)ALARMCONTEXT.getSystemService(Context.ALARM_SERVICE);
	        Calendar calendar = getCalendarObject(the_reminder);
		  long alarmID = calendar.getTimeInMillis();
	        the_reminder.setID((int) alarmID);
		  PendingIntent pendingIntent = getPendingIntent(the_reminder);
	           alarmManager.set(AlarmManager.RTC_WAKEUP, alarmID , pendingIntent);
			return new DatabaseInteractor(ALARMCONTEXT).saveAlarm(the_reminder);
		}
		return false;

	}
	

	   /**
	 * @param the_reminder
	 * @return
	 * 
	 */
	private static PendingIntent getPendingIntent(PaymentReminder the_reminder) {
		if (the_reminder != null)
		{
			Intent broadcastIntent = new Intent(ALARMCONTEXT, AlarmManagerBroadcastReceiver.class);
			broadcastIntent.putExtra(AlarmActivity.ALARMDETAILS, the_reminder);
			return PendingIntent.getBroadcast(ALARMCONTEXT,the_reminder.getID(), broadcastIntent,PendingIntent.FLAG_UPDATE_CURRENT);	  
		}
		return null;
	}



	
	/**
	 * @param the_reminder
	 * @return
	 */
	private static Calendar getCalendarObject(PaymentReminder the_reminder) {
		Calendar calendar = Calendar.getInstance(); 
        calendar.set(Calendar.DAY_OF_MONTH, the_reminder.getDay());
		calendar.set(Calendar.MONTH, the_reminder.getMonth());
		calendar.set(Calendar.YEAR, the_reminder.getYear());
		calendar.set(Calendar.HOUR_OF_DAY, the_reminder.getHour());
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MINUTE, the_reminder.getMinute());
		return calendar;
	
	}


	public static boolean deleteAlarm(PaymentReminder the_reminder)
	{
			if (the_reminder != null)
			{
				  AlarmManager alarmManager =(AlarmManager)ALARMCONTEXT.getSystemService(Context.ALARM_SERVICE);
			        PendingIntent pendingIntent = getPendingIntent(the_reminder);
				  	alarmManager.cancel(pendingIntent);
				  	pendingIntent.cancel();
			       return deleteAlarmFromDB(the_reminder);
			}
			return false;
		}

	/**
	 * @param alarmReceiverService
	 * @param myReminder
	 */
	public static boolean deleteAlarmFromDB(PaymentReminder the_reminder) {
       return new DatabaseInteractor(ALARMCONTEXT).deleteAlarm(the_reminder);
		
	}

	
}
